<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌" prop="carBrand">
        <el-input
          v-model="queryParams.carBrand"
          placeholder="请输入汽车品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车系" prop="carAudi">
        <el-input
          v-model="queryParams.carAudi"
          placeholder="请输入汽车车系"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排量" prop="outputVolume">
        <el-input
          v-model="queryParams.outputVolume"
          placeholder="请输入汽车排量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年款" prop="makeYear">
        <el-input
          v-model="queryParams.makeYear"
          placeholder="请输入汽车年款"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:carModelConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:carModelConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:carModelConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:carModelConfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"  :pageName="$options.name" ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="carModelConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" width="55" align="center" prop="id"   show-overflow-tooltip />
<!--      <el-table-column label="图片" align="center" prop="carBrandPingYing" width="150" >-->
<!--        <template slot-scope="scope">-->
<!--          <el-image-->
<!--            style="width: 200px; height: 100px"-->
<!--            :src="scope.row.carBrandPingYing"-->
<!--            :preview-src-list="[scope.row.carBrandPingYing]"-->
<!--            ></el-image>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="品牌" align="center" prop="carBrand" show-overflow-tooltip />
      <el-table-column label="车系" align="center" prop="carAudi" show-overflow-tooltip />
      <el-table-column label="车型" width="400"  align="center" prop="carModel"  show-overflow-tooltip />
      <el-table-column label="年款" align="center" prop="makeYear"  show-overflow-tooltip />
      <el-table-column label="排量" align="center" prop="outputVolume"  show-overflow-tooltip />
<!--      <el-table-column label="汽车品牌-简拼" align="center" prop="carBrandSpelling" v-if="columns[8].visible" show-overflow-tooltip />-->
<!--      <el-table-column label="汽车品牌-全拼" align="center" prop="carBrandPingYing" v-if="columns[9].visible" show-overflow-tooltip />-->
      <el-table-column label="备注" align="center" prop="remark"  show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车型管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="汽车品牌/车系" prop="brandAudiValue">
<!--          <treeselect-->
<!--            v-model="form.brandAudi"-->
<!--            :options="menuOptions"-->
<!--            :normalizer="normalizer"-->
<!--            :show-count="true"-->
<!--            :disable-branch-nodes="true"-->
<!--            @select="valueChange"-->
<!--            placeholder="选择品牌/车系"-->
<!--          />-->
          <el-cascader
            ref="cascader"
            v-model="form.brandAudiValue"
            :options="menuOptions"
            style="width: 100%"
            :props="carBrandProps"
            @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="制造年款" prop="makeYear" >
          <el-input v-model="form.makeYear" @input="makeYearInput" placeholder="请输入汽车制造年款" >
            <template slot="append">款</template>
          </el-input>
        </el-form-item>
        <el-form-item label="汽车排量" prop="outputVolume" >
          <el-input v-model="form.outputVolume" @input="outputVolumeInput" placeholder="请输入汽车排量"/>
        </el-form-item>
        <el-form-item label="车型简称" prop="carModelSpelling" >
          <el-input v-model="form.carModelSpelling"  @input="carModelSpellingInput" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="车型全称" prop="carModel">
          <el-input v-model="form.carModel" readonly />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCarModelConfig, getCarModelConfig, delCarModelConfig, addCarModelConfig, updateCarModelConfig } from "@/api/system/carModelConfig";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getBrandAudiConfigTree} from "@/api/system/brandAudiConfig";

export default {
  name: "CarModelConfig",
  components: { Treeselect },
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      value: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车型管理表格数据
      carModelConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 菜单树选项
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        states: null,
        carBrand: null,
        carBrandId: null,
        carAudi: null,
        carAudiId: null,
        carModel: null,
        outputVolume: null,
        carModelSpelling: null,
        carBrandPingYing: null,
        isSpecial: null,
        makeYear: null,
        isDeleted: null,
      },
      // 表单参数
      form: {
        brandAudi: null,
      },
      // 表单校验
      rules: {
        brandAudiValue:[
          { required: true, message: "品牌/车系不能为空", trigger: "blur" }
        ],
        carModelSpelling: [
          { required: true, message: "车型简称不能为空", trigger: "blur" }
        ],
        makeYear: [
          { required: true, message: "汽车年款不能为空", trigger: "blur" }
        ],
        outputVolume: [
          { required: true, message: "汽车排量不能为空", trigger: "blur" }
        ],
        carModel: [
          { required: true, message: "汽车车型不能为空", trigger: "blur" }
        ],
      },
      // 列表的列的显示隐藏设置
      columns:[
                  { key: 0, label: `id`, visible: true },
                  { key: 2, label: `汽车品牌`, visible: true },
                  { key: 3, label: `汽车品牌ID`, visible: true },
                  { key: 4, label: `汽车车系`, visible: true },
                  { key: 5, label: `汽车车系ID`, visible: true },
                  { key: 6, label: `汽车车型`, visible: true },
                  { key: 7, label: `汽车排量`, visible: true },
                  { key: 8, label: `汽车品牌-简拼`, visible: true },
                  { key: 9, label: `汽车品牌-全拼`, visible: true },
                  { key: 10, label: `是否特殊品牌`, visible: true },
                  { key: 11, label: `软删除 1-删除；0-正常`, visible: true },
                  { key: 12, label: `创建者`, visible: true },
                  { key: 13, label: `创建时间`, visible: true },
                  { key: 14, label: `更新者`, visible: true },
                  { key: 15, label: `更新时间`, visible: true },
                  { key: 16, label: `备注`, visible: true },
      ],
      carBrandProps: {
        value: "value",
        label: "label",
        checkStrictly: false,
        children: 'children',    //子元素字段名
      },
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    //列表分页列的动态显示配置
    var columns = JSON.parse(localStorage.getItem(this.$options.name));
    if(columns){
      this.columns = columns;
    }
  },
  methods: {
    /** 查询车型管理列表 */
    getList() {
      this.loading = true;
      listCarModelConfig(this.queryParams).then(response => {
        this.carModelConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      let params = {
        isDeleted: 0,
      }
      getBrandAudiConfigTree(params).then(response => {
        this.menuOptions = [];
        // const menu = { id: 0, name: '根',label: '根',  children: [] };
        // menu.children = this.handleTree(response.data, "id");
        // console.log(this.getTreeData(response.data)); // [node,node,node]
        this.menuOptions=this.getTreeData(response.data)
      });
    },
    // 把数据处理成树状结构
    translator(parents, childrens) {
      parents.forEach(item => {
        childrens.forEach(items => {
          if (items.children && !items.children.length) {
            delete items.children;
          }
          if (items.parentId === item.id) {
            item.children ? item.children.push(items) : item.children = [items];
            this.translator([items], childrens);
          }
        })
      })
    },
    getTreeData(arr) {
      let parents = arr.filter(item => item.parentId===0); //取出根节点
      let childrens = arr.filter(item => item.parentId!==0); //去除子节点
      this.translator(parents, childrens)
      return parents
    },
    makeYearInput(value){
      console.log(value);
      this.setCarModelStr(value, this.form.outputVolume, this.form.carModelSpelling)
    },
    outputVolumeInput(value){
      console.log(value);
      this.setCarModelStr(this.form.makeYear, value, this.form.carModelSpelling)
    },
    carModelSpellingInput(value){
      console.log(value);
      this.setCarModelStr(this.form.makeYear, this.form.outputVolume, value)
    },
    setCarModelStr(makeYear, outputVolume, carModelSpelling){
      const result = `${makeYear && makeYear}款  ${outputVolume && outputVolume}  ${carModelSpelling && carModelSpelling}`;
      this.form.carModel = result
    },
    handleChange(data) {
      console.log(data);
      const  values = data;
      this.form.carGroupBrandModels = data
      this.form.brandGroupId = null
      this.form.brandGroup = null
      this.form.carBrand = null
      this.form.carBrandId = null
      this.form.carAudi = null
      this.form.carAudiId = null
      this.form.makeYear = ''
      this.form.carModel = ''
      this.form.outputVolume = ''
      this.form.carModelSpelling = ''
      try {
        let checkedNodes = this.$refs['cascader'].getCheckedNodes()[0];
        console.log(checkedNodes);
        if (checkedNodes) {
          const pathLabels = checkedNodes.pathLabels
          if (pathLabels) {
            this.form.brandGroup = pathLabels[0]
            this.form.brandGroupId = values[0]
            if (pathLabels.length > 1) {
              this.form.carBrand = pathLabels[1]
              this.form.carBrandId = values[1]
            }
            if (pathLabels.length > 2) {
              this.form.carAudi = pathLabels[2]
              this.form.carAudiId = values[2]
            }
            if (pathLabels.length > 3) {
             // this.form.makeYear = pathLabels[3]
            }
          }
        }
        console.log(this.form)
      } catch (error) {
        console.log(error)
      }
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        states: null,
        carBrand: null,
        carBrandId: null,
        carAudi: null,
        carAudiId: null,
        carModel: null,
        outputVolume: null,
        carModelSpelling: null,
        carBrandPingYing: null,
        makeYear: null,
        isSpecial: null,
        isDeleted: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车型管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCarModelConfig(id).then(response => {
        this.form = response.data;
        let brandGroupId = this.form.brandGroupId
        let carBrandId = this.form.carBrandId
        let carAudiId = this.form.carAudiId
        let brandGroupIdStr = `${brandGroupId}`;
        let carBrandIdStr = `${carBrandId}`;
        let carAudiIdStr = `${carAudiId}`;
        this.form.brandAudiValue = [brandGroupIdStr, carBrandIdStr,carAudiIdStr]
        console.log(this.form.brandAudiValue)
        this.open = true;
        this.title = "修改车型管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCarModelConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCarModelConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车型管理编号为"' + ids + '"的数据项？').then(function() {
        return delCarModelConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/carModelConfig/export', {
        ...this.queryParams
      }, `carModelConfig_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
